package com.wwg.myapplication;

import android.content.Intent;
import android.graphics.Canvas;
import android.os.Handler;
import android.os.Looper;

public abstract class Anim {
    protected EnterAnimLayout view;
    protected float w;
    protected float h;
    public float totalPaintTime; // 控制绘制时间

    // 添加帧率控制
    private static final int TARGET_FPS = 60;
    private static final long FRAME_TIME = 1000 / TARGET_FPS; // 16ms per frame

    // 性能优化相关
    private long lastFrameTime = 0;
    private Handler animationHandler;
    private Runnable frameRunnable;
    private boolean isScheduledForNextFrame = false;

    // 动画状态跟踪
    protected boolean isAnimationActive = false;
    protected long animationStartTime = 0;

    public Anim(EnterAnimLayout view) {
        this(view, 2000);
    }

    public Anim(EnterAnimLayout view, float totalPaintTime) {
        this.totalPaintTime = totalPaintTime;
        this.view = view;
        this.view.setAnim(this);
        MainActivity mainActivity = new MainActivity();
        Intent intent =     new Intent(mainActivity.getBaseContext(),this.getClass());

        // 初始化Handler和Runnable
        this.animationHandler = new Handler(Looper.getMainLooper());
        this.frameRunnable = new Runnable() {
            @Override
            public void run() {
                isScheduledForNextFrame = false;
                if (isAnimationActive && !view.ismIsAnimaionRun()) {
                    // 动画被外部停止
                    isAnimationActive = false;
                    return;
                }

                if (isAnimationActive) {
                    long currentTime = System.currentTimeMillis();

                    // 跳帧检测：如果距离上一帧时间过短，跳过这一帧
                    if (currentTime - lastFrameTime >= FRAME_TIME - 2) { // 2ms tolerance
                        lastFrameTime = currentTime;
                        view.invalidate();
                    }

                    scheduleNextFrame();
                }
            }
        };

        updateDimensions();
    }

    public void startAnimation(long animTime) {
        totalPaintTime = animTime;
        isAnimationActive = true;
        animationStartTime = System.currentTimeMillis();
        lastFrameTime = animationStartTime;

        view.setmIsAnimaionRun(true);
        view.setStartTime(animationStartTime);

        // 开始帧调度
        scheduleNextFrame();
    }

    private void scheduleNextFrame() {
        if (!isAnimationActive || isScheduledForNextFrame) return;

        isScheduledForNextFrame = true;

        // 计算到下一帧的延迟时间
        long currentTime = System.currentTimeMillis();
        long elapsedSinceLastFrame = currentTime - lastFrameTime;
        long delay = Math.max(0, FRAME_TIME - elapsedSinceLastFrame);

        animationHandler.postDelayed(frameRunnable, delay);
    }

    public void stopAnimation() {
        isAnimationActive = false;
        view.setmIsAnimaionRun(false);

        // 清除待执行的帧
        if (animationHandler != null && frameRunnable != null) {
            animationHandler.removeCallbacks(frameRunnable);
        }
        isScheduledForNextFrame = false;
    }

    protected void updateDimensions() {
        w = view.getWidth();
        h = view.getHeight();
    }

    // 获取当前动画进度 (0.0 - 1.0)
    protected float getCurrentProgress() {
        if (!isAnimationActive) return 0f;

        long currentTime = System.currentTimeMillis();
        long elapsed = currentTime - animationStartTime;
        return Math.min(1.0f, elapsed / totalPaintTime);
    }

    // 检查动画是否应该继续
    protected boolean shouldContinueAnimation() {
        return isAnimationActive && view.ismIsAnimaionRun() && getCurrentProgress() < 1.0f;
    }

    // 子类必须实现的方法
    public abstract void handleCanvas(Canvas canvas, float rate);

    // 添加重置方法（子类可以覆盖它）
    public void reset() {
        stopAnimation();
        // 基类中为空实现，子类可以添加特定的重置逻辑
    }

    // 获取动画是否正在运行
    public boolean isRunning() {
        return isAnimationActive && view.ismIsAnimaionRun();
    }

    // 获取总动画时长
    public float getTotalPaintTime() {
        return totalPaintTime;
    }

    // 设置总动画时长
    public void setTotalPaintTime(float totalPaintTime) {
        this.totalPaintTime = totalPaintTime;
    }

    // 清理资源
    public void cleanup() {
        stopAnimation();
        if (animationHandler != null && frameRunnable != null) {
            animationHandler.removeCallbacks(frameRunnable);
        }
        animationHandler = null;
        frameRunnable = null;
    }
}